package com.cksys.achievement.controller;

import com.cksys.achievement.entity.Result;
import com.cksys.achievement.entity.ResultUser;
import com.cksys.achievement.entity.Type;
import com.cksys.achievement.entity.User;
import com.cksys.achievement.enums.ResultStatus;
import com.cksys.achievement.service.IResultService;
import com.cksys.achievement.service.IResultUserService;
import com.cksys.achievement.service.ISettingService;
import com.cksys.achievement.service.ITypeService;
import com.cksys.achievement.utils.ExcelUtil;
import com.cksys.achievement.utils.RestResponse;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName: ExcelContrller
 * @author: zyx
 * @E-mail: 1377631190@qq.com
 * @DATE: 2020/3/12 22:48
 */
@RestController
public class ExcelController {

    @Autowired
    ExcelUtil excelUtil;

    @Autowired
    IResultService resultService;

    @Autowired
    IResultUserService resultUserService;

    @Autowired
    ITypeService typeService;

    @Autowired
    ISettingService settingService;

    @PostMapping("/excel/import")
    public RestResponse importExcel(@RequestParam("file") MultipartFile file) throws IOException {
        List<Result> results = excelUtil.importResult(file.getInputStream());

        Boolean autoAudited = settingService.getById(1).getAutoAudited();

        boolean b = false;
        for (Result result : results) {
            if (autoAudited) {
                result.setResultStatus(ResultStatus.PASSED);
            } else {
                result.setResultStatus(ResultStatus.UNAUDITED);
            }
            result.setInsertTime(LocalDateTime.now());
            b = resultService.saveOrUpdate(result);
            if (b) {
                if (result.getUserList() != null) {
                    List<User> userList = result.getUserList();
                    userList.stream()
                            .filter(t -> !result.getUId().equals(t.getId()))
                            .forEach(j -> {
                                resultUserService.save(new ResultUser()
                                        .setRId(result.getId())
                                        .setUId(j.getId())
                                        .setIsLeader(false));
                    });
                }
                resultUserService.save(new ResultUser().setRId(result.getId()).setUId(result.getUId()).setIsLeader(true));
            }
        }
        if (b) {
            return RestResponse.ok("导入成功！");
        } else {
            return RestResponse.fail("导入失败！");
        }

    }

    @GetMapping("/download/demo")
    public void downloadDemo(HttpServletResponse response) {
        XSSFWorkbook workBook = excelUtil.createWorkBook();
        XSSFSheet sheet = workBook.createSheet("成果统计表");

        sheet.setColumnWidth(0, ExcelUtil.TITLE_WIDTH_X * 256);
        sheet.setColumnWidth(1, ExcelUtil.TITLE_WIDTH_X * 256);
        sheet.setColumnWidth(2, ExcelUtil.TITLE_WIDTH_X * 256);
        sheet.setColumnWidth(3, ExcelUtil.TITLE_WIDTH_X * 256);
        sheet.setColumnWidth(4, ExcelUtil.TITLE_WIDTH_X * 256);
        sheet.setColumnWidth(5, ExcelUtil.TITLE_WIDTH_X * 256);
        sheet.setColumnWidth(6, ( ExcelUtil.TITLE_WIDTH_X + 5 ) * 256);

        CellStyle contentStyle = excelUtil.getContentStyle(workBook);
        CellStyle titleType = excelUtil.getTitleType(workBook);

        String[] titles = {"成果名称", "队长ID", "成果类型", "成果链接", "获得时间", "成果简介", "合伙人ID(以,分隔)"};
        excelUtil.setTitle(titles.length, "软件开发创客实验室成果统计表", sheet, titleType);
        excelUtil.setContent(titles, sheet, contentStyle);
        List<String> titleList = Arrays.asList(titles);

        String[] textList = {};
        textList = typeService.list().stream().map(Type::getName).collect(Collectors.toList()).toArray(textList);

        int getTimeIndex = titleList.indexOf("获得时间");
        int infoIndex = titleList.indexOf("成果简介");
        int typeIndex = titleList.indexOf("成果类型");
        int nameIndex = titleList.indexOf("成果名称");
        int leaderNameIndex = titleList.indexOf("队长ID");

        excelUtil.setLengthValidation(sheet, 255, ExcelUtil.CONTENT_START_ROW, ExcelUtil.ALL_ROWS, nameIndex, nameIndex);
        excelUtil.setLengthValidation(sheet, 255, ExcelUtil.CONTENT_START_ROW, ExcelUtil.ALL_ROWS, leaderNameIndex, leaderNameIndex);
        excelUtil.setLengthValidation(sheet, 255, ExcelUtil.CONTENT_START_ROW, ExcelUtil.ALL_ROWS, infoIndex, infoIndex);
        excelUtil.setTypeValidation(sheet, textList, ExcelUtil.CONTENT_START_ROW, ExcelUtil.ALL_ROWS, typeIndex, typeIndex);
        excelUtil.setTimeValidation(sheet, ExcelUtil.CONTENT_START_ROW, ExcelUtil.ALL_ROWS, getTimeIndex, getTimeIndex);

        excelUtil.download(response, workBook, "成果统计表.xlsx");
    }

    @GetMapping("/excel/export")
    public void export(@RequestParam(value = "time", required = false) String time,
                       @RequestParam(value = "type", required = false) Integer typeId,
                       @RequestParam(value = "userIds", required = false) List<Integer> userIds,
                       @RequestParam(value = "resultStatus", required = false) ResultStatus resultStatus,
                       HttpServletResponse response) {
        List<Result> resultList = resultService.searchResultList(time, typeId, userIds, null, resultStatus);

        XSSFWorkbook workBook = excelUtil.createWorkBook();
        XSSFSheet sheet = workBook.createSheet("成果统计表");

        sheet.setColumnWidth(0, ExcelUtil.TITLE_WIDTH_X * 256);
        sheet.setColumnWidth(1, ExcelUtil.TITLE_WIDTH_X * 256);
        sheet.setColumnWidth(2, ExcelUtil.TITLE_WIDTH_X * 256);
        sheet.setColumnWidth(3, ExcelUtil.TITLE_WIDTH_X * 256);
        sheet.setColumnWidth(4, ExcelUtil.TITLE_WIDTH_X * 256);
        sheet.setColumnWidth(5, ExcelUtil.TITLE_WIDTH_X * 256);
        sheet.setColumnWidth(6, ( ExcelUtil.TITLE_WIDTH_X + 5 ) * 256);

        CellStyle contentStyle = excelUtil.getContentStyle(workBook);
        CellStyle titleType = excelUtil.getTitleType(workBook);
        CellStyle resultContentStyle = excelUtil.getResultContentStyle(workBook);

        String[] titles = {"成果名称", "队长名称", "成果类型", "成果链接", "获得时间", "成果简介", "合伙人名称(以,分隔)"};
        excelUtil.setTitle(titles.length, "软件开发创客实验室成果统计表", sheet, titleType);
        excelUtil.setContent(titles, sheet, contentStyle);

        excelUtil.setContent(resultList, titles.length, sheet, resultContentStyle);

        excelUtil.download(response, workBook, "成果统计表.xlsx");
    }

}
